package niu.toy.spring.mvc.impl;

import niu.toy.spring.mvc.View;
import niu.toy.spring.mvc.ViewResolver;


import java.util.Locale;

/**
 * 视图解析器：viewName返回视图对象，核心逻辑在View
 * @author niu
 */
public class InternalResourceViewResolver implements ViewResolver {
    //前缀用于区分是redirect还是forward
    public static final String REDIRECT_URL_PREFIX = "redirect:";
    public static final String FORWARD_URL_PREFIX = "forward:";

    private String prefix = "";
    private String suffix = ".html";


    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        // Check for special "redirect:" prefix.
        if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
            String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length());
            RedirectView view = new RedirectView(redirectUrl);
            return  view;
        }
        // Check for special "forward:" prefix.
        String forwardUrl=viewName;
        if (viewName.startsWith(FORWARD_URL_PREFIX)) {
            forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length());
        }
        return new InternalResourceView(forwardUrl+this.suffix);
    }



}
